package com.hsy.order.utils

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hsy.order.Application
import com.hsy.order.R
import com.hsy.order.base.Config

import com.hsy.order.base.ui.widget.ProgressDialog
import com.hsy.order.login.ui.LoginActivity
import android.content.pm.PackageManager
import com.flux.utils.LogUtil


/**
 * 通用工具
 * Created on 2017/8/28.
 *
 * @author Yang
 */
object CommonUtils {

    private const val KEY_TOKEN = "key_token"
    private const val KEY_USER_ID = "KEY_USER_ID"
    private const val KEY_IM_ID = "KEY_IM_ID"
    private const val KEY_INTERVAL = "key_Interval"
    private const val KEY_ACCEPT = "key_accept"
    private const val KEY_DISPATCH = "key_dispatch"
    private const val KEY_PRINT_NUM = "key_print_num"
    private const val KEY_VERSION_CODE = "key_version_code"
    private const val KEY_DEVICE_ADDRESS = "KEY_DEVICE_ADDRESS"
    private var INVALID_TOKEN = "-1"

    private fun getSharePreferences() = Application.instance.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)

    /**
     * 保存用户ID
     */
    fun saveUserId(id: String) = getSharePreferences().edit().putString(KEY_USER_ID, id).apply()

    /**
     * 获取用户ID
     */
    fun getUserId() = getSharePreferences().getString(KEY_USER_ID, "-1")!!

    /**
     * 保存ImID
     */
    fun saveImId(id: String) = getSharePreferences().edit().putString(KEY_IM_ID, id).apply()

    /**
     * 获取ImID
     */
    fun getImId() = getSharePreferences().getString(KEY_IM_ID, "-1")!!

    /**
     * 保存用户Token
     */
    fun saveToken(token: String) = getSharePreferences().edit().putString(KEY_TOKEN, token).apply()

    /**
     * 获取用户Token
     */
    fun getToken() = getSharePreferences().getString(KEY_TOKEN, INVALID_TOKEN)!!

    /**
     * 清空用户Token
     */
    fun clearToken() {
        getSharePreferences().edit().remove(KEY_TOKEN).apply()
        getSharePreferences().edit().remove(KEY_USER_ID).apply()
        getSharePreferences().edit().remove(KEY_IM_ID).apply()
        getSharePreferences().edit().remove(KEY_INTERVAL).apply()
        getSharePreferences().edit().remove(KEY_ACCEPT).apply()
    }


    /**
     * 检查用户是否登录
     */
    fun checkLogin() = INVALID_TOKEN != getToken()

    /**
     * 保存蓝牙设备地址
     */
    fun saveDeviceAddress(address: String) = getSharePreferences().edit().putString(KEY_DEVICE_ADDRESS, address).apply()

    /**
     * 获取蓝牙设备地址
     */
    fun getDeviceAddress() = getSharePreferences().getString(KEY_DEVICE_ADDRESS, "")!!

    /**
     * 保存刷新间隔
     */
    fun saveReloadInterval(interval: Long) = getSharePreferences().edit().putLong(KEY_INTERVAL, interval).apply()

    /**
     * 获取刷新间隔
     */
    fun getReloadInterval() = getSharePreferences().getLong(KEY_INTERVAL, 60) * 1000L

    /**
     * 保存是否自动接单
     */
    fun saveAutoAccept(auto: String) = getSharePreferences().edit().putString(KEY_ACCEPT, auto).apply()

    /**
     * 获取是否自动接单
     */
    fun getAutoAccept() = getSharePreferences().getString(KEY_ACCEPT, "a")!! == getUserId()

    /**
     * 保存是否自动接单
     */
    fun saveAutoDispatch(auto: String) = getSharePreferences().edit().putString(KEY_DISPATCH, auto).apply()

    /**
     * 获取是否自动派单
     */
    fun getAutoDispatch() = getSharePreferences().getString(KEY_DISPATCH, "a")!! == getUserId()

    /**
     * 保存打印数量
     */
    fun savePrintNum(num: Int) = getSharePreferences().edit().putInt(KEY_PRINT_NUM, num).apply()

    /**
     * 获取打印数量
     */
    fun getPrintNum() = getSharePreferences().getInt(KEY_PRINT_NUM, 1)

    /**
     * 保存打印数量
     */
    fun saveVersionCode(version: Int) = getSharePreferences().edit().putInt(KEY_VERSION_CODE, version).apply()

    /**
     * 获取打印数量
     */
    fun getVersionCode() = getSharePreferences().getInt(KEY_VERSION_CODE, 0)

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    fun getVerName(context: Context): String {
        var verName = ""
        try {
            verName = context.packageManager.getPackageInfo(context.packageName, 0).versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }

        return verName
    }

    private var authFailureDialog: Dialog? = null

    val isAuthDialogShowing: Boolean
        get() = authFailureDialog?.isShowing ?: false

    /**
     * 进度对话框
     */
    private var mProgressDialog: Dialog? = null

    /**
     * 进度对话框是否在显示
     */
    val isProgressDialogShowing: Boolean
        get() = null != mProgressDialog && mProgressDialog!!.isShowing

    /**
     * 显示进度对话框
     */
    fun showProgressDialog(context: Context?) {
        if (null == mProgressDialog || !mProgressDialog!!.isShowing) {
            mProgressDialog = ProgressDialog(context)
        }
        mProgressDialog!!.show()
        LogUtil.i("showProgressDialog")
    }

    /**
     * 隐藏进度对话框
     */
    fun hideProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog!!.dismiss()
            mProgressDialog = null
        }
    }

    fun showAuthFailureDialog(activityContext: Context, msg: String) {
        hideProgressDialog()
        val builder = AlertDialog.Builder(activityContext)
                .setMessage(msg)
                .setPositiveButton(R.string.button_confirm) { _, _ ->
                    activityContext.startActivity(Intent(activityContext, LoginActivity::class.java))
                }
                .setCancelable(false)

        authFailureDialog = builder.create()
        authFailureDialog!!.setOnDismissListener { _ ->
            authFailureDialog = null
            clearToken()
            activityContext.startActivity(Intent(activityContext, LoginActivity::class.java))
        }
        authFailureDialog!!.show()
        Handler().postDelayed({
            if (null != authFailureDialog) {
                authFailureDialog!!.dismiss()
            }
        }, 5000)
    }

    fun showNetworkFailure(context: Context, container: ViewGroup, onRefreshListener: View.OnClickListener?, index: Int = -1): View {
        val webViewFailurePage = LayoutInflater.from(context).inflate(R.layout.webview_failure_page, container, false)
        container.addView(webViewFailurePage, index, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        if (null != onRefreshListener) {
            webViewFailurePage.setOnClickListener(onRefreshListener)
        }
        return webViewFailurePage
    }
}